<template>
  <div>
    <div>
      <button @click="queryStudents">查询学生信息</button>
      <button @click="downloadStudents">下载</button>
    </div>

    <table v-if="students">
      <thead>
        <tr>
          <th>学号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="student in students" :key="student.sid">
          <td>{{ student.sid }}</td>
          <td>{{ student.sname }}</td>
          <td>{{ student.sage }}</td>
          <td>{{ student.ssex }}</td>
        </tr>
      </tbody>
    </table>
    <p v-if="!students && loading">正在加载...</p>
    <p v-if="!students && !loading">暂无信息</p>

      
    <!-- 分页按钮，显示当前页面/总页面 -->
    <div v-if="totalPages > 1">
      <button :disabled="currentPage === 1" @click="prevPage">上一页</button>
      <button :disabled="currentPage === totalPages" @click="nextPage">下一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>

        <select v-model="pageSize" @change="queryStudents">
        <option v-for="size in pageSizes" :value="size">{{ size }} 条/页</option>
      </select>
    </div>

  </div>
</template>
<script>
export default {
  data() {
    return {
      students: null,
      totalPages: 1,
      currentPage: 1,
      pageSize: 6,
      pageSizes: [6, 12, 24],
      loading: false
    }
  },
  methods: {
    queryStudents() {
      this.loading = true;
      this.$axios.get(`/getStudents?page=${this.currentPage}&pageSize=${this.pageSize}`).then(response => {
        this.students = response.data.data// 获取学生信息列表
        this.totalPages = response.data.totalPages// 获取总页数
        this.loading = false;
      }).catch(error => {
        console.log(error)
        this.loading = false;
      })
    },
    downloadStudents() {// 下载请求
      this.$axios.get('/download', { responseType: 'blob' }).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '学生信息表.xlsx')
        document.body.appendChild(link)
        link.click()
      }).catch(error => {
        console.log(error)
      })
    },
    prevPage() {
      this.currentPage -= 1;
      this.queryStudents(); // 发送请求查询上一页学生信息
    },
    nextPage() {
      this.currentPage += 1;
      this.queryStudents(); // 发送请求查询下一页学生信息
    }
  }
}
</script>

<style scoped>
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  text-align: left;
  padding: 8px;
  border-bottom: 1px solid #ddd;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}
</style>
